package account_manage

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/widget"
	"golang.org/x/image/colornames"
	"time"
)

type loadingView struct {
	win         fyne.Window
	popUp       *widget.PopUp
	text        *canvas.Text
	isShow      bool
	isLoop      bool
	TextStr     string
	TextStrList []string
}

var CurLoadingView *loadingView

// LoadingView 初始化加载视图
func LoadingView() *loadingView {
	if CurLoadingView != nil {
		return CurLoadingView
	}

	_loadingWin := initLoadingView(
		"加载中...",
		80,
		[]string{"加载中.", "加载中..", "加载中..."},
	)
	CurLoadingView = _loadingWin

	return _loadingWin
}

func initLoadingView(textStr string, textSize float32, textStrList []string) *loadingView {
	_loadingWin := &loadingView{
		TextStr:     textStr,
		TextStrList: textStrList,
	}

	if drv, ok := fyne.CurrentApp().Driver().(desktop.Driver); ok {
		w := drv.CreateSplashWindow()
		_text := &canvas.Text{
			Text:     _loadingWin.TextStr,
			TextSize: textSize,
			Color:    colornames.Gray,
		}

		w.SetContent(_text)
		w.CenterOnScreen()
		w.Resize(fyne.NewSize(150, 0))
		_loadingWin.win = w
		_loadingWin.text = _text
	}

	return _loadingWin
}

func (l *loadingView) Show() *loadingView {
	if l.win == nil || l.isShow {
		//logger.Print("loading已显示")
		return nil
	}

	l.isShow = true
	l.win.Show()
	//logger.Print("显示loading")

	go func() {
		if !l.isShow || l.isLoop {
			//logger.Print("loading刷新return isShow:%s isLoop:%s", l.isShow, l.isLoop)
			return
		}

		//logger.Print("开始loading刷新")
		l.isLoop = true
		_ticker := time.NewTicker(time.Millisecond * 500)
		defer _ticker.Stop()
		_curIdx := 0
		for {
			if !l.isShow {
				//logger.Print("loading隐藏，结束loading刷新")
				break
			}
			select {
			case <-_ticker.C:
				l.text.Text = l.TextStrList[_curIdx]
				l.text.Refresh()
				_curIdx++
				if _curIdx >= len(l.TextStrList) {
					_curIdx = 0
				}
			}
		}
		l.isLoop = false
		l.Hide()
		//fmt.Println("over...")
	}()

	return l
}

func (l *loadingView) Hide() {
	//logger.Print("隐藏loading")
	l.isShow = false
	l.win.Hide()
}

func (l *loadingView) Close() {
	l.win.Close()
}
